import React from 'react';
import {
  Modal,
  Select,
  Form,
  Button,
  message,
} from 'antd';
import { listUser, updateUser } from 'services/user';
import { listDeployment } from 'services/deployment';
import TableWithSearch from 'components/TableWithSearch';
import { addRelation, userECNList } from 'services/ecn';
import { getUserId, getToken } from 'services/token';

const { Option } = Select;
let chosenId = '';
class UserManage extends React.Component {
  constructor() {
    super();
    this.selectedUser = null;
    this.state = {
      userList: [],
      publishedInstanceOptions: [],
      visible: false,
      ecnModalVisible: false,
      selectedECNs: [],
    };
  }

  roleList = ['运维人员', '管理人员', '工艺人员', '操作人员'];

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = () => {
    const { form } = this.props;
    this.setState({
      visible: false,
    });
    updateUser({
      userId: chosenId,
      newRole: form.getFieldValue('select'),
    })
      .then(this.getUserInfo);
  };

  handleECNSelect = () => {
    const { form } = this.props;
    this.setState({
      ecnModalVisible: false,
    });
    const ecns = form.getFieldValue('selectECNs');
    // console.log(ecns);
    // console.log({
    //   userId: this.selectedUser,
    //   instanceIdList: ecns,
    // });

    addRelation({
      userId: this.selectedUser,
      instanceIdList: ecns,
    }).then(() => {
      message.success('添加成功！');
    });
  }

  handleCancel = () => {
    this.setState({
      visible: false,
      ecnModalVisible: false,
    });
  };

  getUserInfo = () => {
    listUser()
      .then((dataList) => {
        this.setState({ userList: dataList });
      });
  };

  componentDidMount() {
    this.getUserInfo();
    listDeployment()
      .then((data) => {
        const options = data
          .filter((instance) => instance.publishStatus)
          .map((instance) => (
            <Option key={instance.instanceId}>{instance.name}</Option>
          ));
        this.setState({
          publishedInstanceOptions: options,
        });
      });
  }

  render() {
    const { form } = this.props;
    const {
      userList, visible, ecnModalVisible, publishedInstanceOptions, selectedECNs,
    } = this.state;
    const { getFieldDecorator } = form;
    const formattedUserList = userList.map((item) => ({
      ...item,
      username: item.username || '',
      phone: item.phone || '',
      role: this.roleList[item.role],
    }));
    const columns = [
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
      },
      {
        title: '工号',
        dataIndex: 'userId',
        key: 'userId',
      },
      {
        title: '角色',
        dataIndex: 'role',
        key: 'role',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <>
            <Button
              size="small"
              style={{ marginRight: '10px' }}
              onClick={() => {
                chosenId = record.userId;
                form.setFieldsValue({ select: record.role });
                this.showModal();
              }}
            >
            修改用户角色
            </Button>
            {
              record.role === '操作人员'
                ? (
                  <Button
                    size="small"
                    style={{ marginRight: '10px' }}
                    onClick={async () => {
                      this.selectedUser = record.userId;
                      try {
                        const user = getUserId(getToken());
                        const ecns = (await userECNList(record.userId))
                          .filter((ecn) => ecn.source === user)
                          .map((ecn) => ecn.instanceId)
                          .map((id) => id.split(/\./)[0].substring(7)); // http://{name}.{user}:{port}
                        this.setState({
                          ecnModalVisible: true,
                          selectedECNs: ecns,
                        });
                      } catch (error) {
                        console.error(error);
                      }
                    }}
                  >
                  绑定服务列表
                  </Button>
                )
                : null
            }
          </>
        ),
      },
    ];
    return (
      <>
        <TableWithSearch
          rowKey="userId"
          size="middle"
          columns={columns}
          dataSource={formattedUserList}
        />
        <Modal
          title="修改用户角色"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          {getFieldDecorator('select', {
            initialValue: form.getFieldValue('select'),
          })(
            <Select style={{ width: '32%' }}>
              <Option value="0">运维人员</Option>
              <Option value="1">管理人员</Option>
              <Option value="2">工艺人员</Option>
              <Option value="3">操作人员</Option>
            </Select>,
          )}
        </Modal>
        <Modal
          title="绑定服务列表"
          visible={ecnModalVisible}
          onOk={this.handleECNSelect}
          onCancel={() => {
            this.setState({
              ecnModalVisible: false,
            });
          }}
        >
          {getFieldDecorator('selectECNs', {
            initialValue: selectedECNs,
          })(
            <Select
              mode="multiple"
              style={{ width: '32%' }}
              placeholder="请选择服务"
            >
              {publishedInstanceOptions}
            </Select>,
          )}
        </Modal>
      </>
    );
  }
}

export default Form.create({})(UserManage);
